<script setup lang="ts">
import { ref } from 'vue'
import { checkMoible } from '@/utils/validate'
import { addUserApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()

const formRef = ref()
const formData = ref({
  username: '',
  password: '',
  mobile: '',
})

// 表单校验规则
// rule:规则，没有用
// value:表单输入数据
// callback:函数  数据不管合法与不合法都要调用callback
// 合法：callback()                           相当于next()
// 不合法： callback(new Error('提示信息'))    相当于next(false)

const validateMobile = (rule: object, value: string, callback: (arg0?: object) => void) => {
  if (checkMoible(value)) {
    callback()
  } else {
    callback(new Error('手机号不合法'))
  }
}

const formRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度应在6~12位之间', trigger: 'blur' },
  ],
  mobile: [{ validator: validateMobile, trigger: 'blur' }],
}

// 新增用户
const addUser = () => {
  // 1.兜底校验
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    // 2.ajax新增用户
    const res = await addUserApi(formData.value)

    if (res.data.state !== 201) {
      return ElMessage.error(res.data.msg)
    }

    // 3.成功提示
    ElMessage.success('新增用户成功')
    // 4.跳转到用户列表页
    router.push('/user')
  })
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>用户创建</span>
      </div>
    </template>

    <!-- 新增用户表单 -->
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto" size="large">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">立即创建</el-button>
        <el-button @click="formRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss"></style>
